package com.benjaminwan.read.free.utils

import android.content.SharedPreferences
import com.benjaminwan.read.free.model.moshiadapter.ActionAdapter
import com.benjaminwan.read.free.model.moshiadapter.IntRangeAdapter
import com.benjaminwan.read.free.model.moshiadapter.LongRangeAdapter
import com.squareup.moshi.Moshi
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty

val actionMoshi: Moshi by lazy {
    Moshi.Builder()
        .add(IntRangeAdapter)
        .add(LongRangeAdapter)
        .add(ActionAdapter)
        .build()
}

inline fun <reified T> toActionJsonByMoshi(src: T): String {
    val jsonAdapter = actionMoshi.adapter<T>(T::class.java)
    return jsonAdapter.toJson(src)
}

inline fun <reified T> fromJsonToActionByMoshi(json: String): T? {
    val jsonAdapter =
        actionMoshi.adapter<T>(T::class.java)
    try {
        return jsonAdapter.fromJson(json)
    } catch (e: Exception) {
        e.printStackTrace()
    }
    return null
}

/**
 * 使用moshi+SharedPreferences 任意对象 读写代理
 * @param  key 存储key
 * @param  defValue 默认值
 * @return 返回代理
 */
inline fun <reified T> SharedPreferences.moshiActionAny(key: String, defValue: T) =
    object : ReadWriteProperty<Any, T> {
        override fun getValue(thisRef: Any, property: KProperty<*>): T {
            if (!contains(key)) {
                return defValue
            }
            val value = getString(key, "")
            if (value.isNullOrEmpty()) {
                return defValue
            }
            return fromJsonToActionByMoshi(value) ?: defValue
        }

        override fun setValue(thisRef: Any, property: KProperty<*>, value: T) {
            value ?: return edit().putString(key, "").apply()
            return edit().putString(key, toActionJsonByMoshi(value)).apply()
        }
    }